package com.tenton.service.impl;

import com.tenton.MyException.DataNotExist;
import com.tenton.mapper.AdministratorMapper;
import com.tenton.pojo.Administrator;
import com.tenton.service.AdministratorService;
import com.tenton.utils.Constants;
import com.tenton.utils.IntegerUtils;
import com.tenton.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @Date: 2021/1/9
 * @Author: Tenton
 * @Description:
 */
@Service
public class AdministratorServiceImpl implements AdministratorService {
    @Autowired
    AdministratorMapper administratorMapper;

    /**
     * 登录验证
     *
     * @param adminName
     * @param pwd
     * @return
     */
    @Override
    public boolean getLogin(String adminName, String pwd, HttpSession session) {
        if (StringUtils.isEmpty(adminName) && StringUtils.isEmpty(pwd)) {
            throw new NullPointerException("用户名或密码为空");
        } else {
            Administrator administrator = administratorMapper.getLogin(adminName, pwd);
            if (administrator != null) {
                session.setAttribute("userId", administrator.getId());
                session.setAttribute("name", adminName);
                session.setAttribute(Constants.ADMIN_SESSION, administrator);
                return true;
            }
        }
        return false;
    }

    /**
     * 获取管理员信息
     *
     * @param id
     * @param model
     */
    @Override
    public void getAdminById(Integer id, Model model) {
        if (IntegerUtils.isEmpty(id)) {
            throw new NullPointerException("管理员Id为空");
        } else {
            Administrator administrator = administratorMapper.selectByPrimaryKey(id);
            model.addAttribute("admin", administrator);
        }
    }

    /**
     * 修改
     *
     * @param administrator
     * @param model
     * @throws DataNotExist
     */
    @Override
    public void update(Administrator administrator, Model model) throws DataNotExist {
        if (administrator == null) {
            throw new DataNotExist("管理员信息为空");
        }else {
            administratorMapper.updateByPrimaryKey(administrator);
            model.addAttribute("admin", administrator);
        }
    }
}
